package com.hundsun.yr.universal.p2p.ui.activity;

import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseMineWebActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONException;
import org.json.JSONObject;

import de.greenrobot.event.EventBus;


/**
 * @version V1.0
 * @Title: WebPayActivity.java
 * @Description: 支付WEB--支付页面h5
 * @date 2016-3-16 下午7:14:15
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class WebRiskActivity extends BaseMineWebActivity implements OnClickListener ,InitializeView{

    /**
     * 跳转标识
     */
    public String NAVIGATE_TAG;
    private RequestPresenter presenter;
    public HSSharedPreferences sharedPreferences = null;
    private String zwgt_data;

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {

        if (mBrowserLayout == null) {
        }
        return mBrowserLayout;
    }


    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        mBrowserLayout.refresh();
        toggleHide();
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        NAVIGATE_TAG = extras.getString(Extras.NAVIGATE_TAG);
    }

    @Override
    protected void onNetworkDisConnected() {

        toggleNetworkError(true, new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (NetUtils.isNetworkConnected(getBaseContext())) {
                    showToast("请检查网络...");
                } else {
                    mBrowserLayout.refresh();
                    toggleHide();
                }
            }
        });

    }


    @Override
    protected void initViewsAndEvents() {
        super.initViewsAndEvents();
        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);
        syncCookie(mContext,mWebUrl);
        toolbar_title.setText(mWebTitle);
        toolbar_menu.setText(R.string.complete);
        toolbar_menu.setTextColor(getResources().getColor(R.color.white));
        toolbar_menu.setVisibility(View.GONE);
        toolbar_menu.setOnClickListener(this);
        mToolBar.setOnClickListener(this);
        mToolBar.setNavigationOnClickListener(this);

        presenter = new InitializePresenterImpl(this,this);

        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);

        mBrowserLayout.getWebView().getSettings().setJavaScriptEnabled(true);
        mBrowserLayout.getWebView().addJavascriptInterface(WebRiskActivity.this, "wjj");

        mBrowserLayout.mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                mWebUrl = url;
                return true;
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
            }
        });

        mBrowserLayout.mWebView.getSettings().setSupportZoom(true);
        mBrowserLayout.mWebView.getSettings().setBuiltInZoomControls(true);
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onClick(View v) {
        webBack();
    }



    @Override
    protected void onDestroy() {
//        EventBus.getDefault().post(new EventCenter(Constants.EVENT_REFRESH_AUTOMATIC_LOGIN));//登陆成功通知某些页面进行数据刷新
        super.onDestroy();
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        //成功之后才关闭
        finish();
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            webBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 网页 返回
     */
    public void webBack() {
        //刷新自动登录接口
        automaticLogin();
    }

    private void automaticLogin() {
        if (sharedPreferences.getShareProf(UserInfo.TOKENID) != null && !sharedPreferences.getShareProf(UserInfo.TOKENID).isEmpty()){
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            JSONObject map = new JSONObject();
            try {
                map.put("token", sharedPreferences.getShareProf(UserInfo.TOKENID));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
            presenter.loadingData(TaskConstants.TASK_LOGINSILENT, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data),true);
        }
    }

    @JavascriptInterface
    public void investList (){
        webBack();
        if (BaseAppManager.getInstance().getActivity(ManagementActivity.class) != null) {
            BaseAppManager.getInstance().getActivity(ManagementActivity.class).finish();
        }
        EventBus.getDefault().post(new EventCenter(Extras.RECHARGE_SUCCESS_GO_TO_PROJECT));
    }
}
